﻿<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
<div id="app" class="common-layout" style="max-width: max-content;">
    <div id="tableBlock">

        <!-- 概览统计卡片 -->
        <div class="overview-stats">
            <el-card class="stat-card" hoverable>
                <div class="stat-content">
                    <div class="stat-info">
                        <div class="stat-label">库存总数量</div>
                        <div class="stat-value">{{overviewData.totalInventory || 0}}</div>
                        <div class="stat-trend" :class="overviewData.inventoryTrend > 0 ? 'up' : 'down'">
                            <el-icon size="16">
                                <component :is="overviewData.inventoryTrend > 0 ? 'CaretTop' : 'CaretBottom'"></component>
                            </el-icon>
                            <span>{{ Math.abs(overviewData.inventoryTrend) || 0 }}%</span>
                        </div>
                    </div>
                    <div class="stat-icon">📦</div>
                </div>
            </el-card>

            <el-card class="stat-card" hoverable>
                <div class="stat-content">
                    <div class="stat-info">
                        <div class="stat-label">库存总金额</div>
                        <div class="stat-value">¥{{ (overviewData.totalInventoryValue || 0).toLocaleString() }}</div>
                        <div class="stat-trend" :class="overviewData.valueTrend > 0 ? 'up' : 'down'">
                            <el-icon size="16">
                                <component :is="overviewData.valueTrend > 0 ? 'CaretTop' : 'CaretBottom'"></component>
                            </el-icon>
                            <span>{{ Math.abs(overviewData.valueTrend) || 0 }}%</span>
                        </div>
                    </div>
                    <div class="stat-icon">💰</div>
                </div>
            </el-card>

            <el-card class="stat-card" hoverable>
                <div class="stat-content">
                    <div class="stat-info">
                        <div class="stat-label">今日入库</div>
                        <div class="stat-value">{{overviewData.todayInbound || 0}}</div>
                        <div class="stat-trend" :class="overviewData.inboundTrend > 0 ? 'up' : 'down'">
                            <el-icon size="16">
                                <component :is="overviewData.inboundTrend > 0 ? 'CaretTop' : 'CaretBottom'"></component>
                            </el-icon>
                            <span>{{ Math.abs(overviewData.inboundTrend) || 0 }}%</span>
                        </div>
                    </div>
                    <div class="stat-icon">📥</div>
                </div>
            </el-card>

            <el-card class="stat-card" hoverable>
                <div class="stat-content">
                    <div class="stat-info">
                        <div class="stat-label">今日出库</div>
                        <div class="stat-value">{{overviewData.todayOutbound || 0}}</div>
                        <div class="stat-trend" :class="overviewData.outboundTrend > 0 ? 'up' : 'down'">
                            <el-icon size="16">
                                <component :is="overviewData.outboundTrend > 0 ? 'CaretTop' : 'CaretBottom'"></component>
                            </el-icon>
                            <span>{{ Math.abs(overviewData.outboundTrend) || 0 }}%</span>
                        </div>
                    </div>
                    <div class="stat-icon">📤</div>
                </div>
            </el-card>
        </div>

        <!-- 饼图区域 -->
        <div class="charts-section">
            <el-card class="chart-card">
                <div class="chart-header">
                    <span>库存货品类型分布:</span>
                </div>
                <div id="categoryPieChart" class="chart-container"></div>
            </el-card>

            <el-card class="chart-card">
                <div class="chart-header">
                    <span>货品库存占比:</span>
                </div>
                <div id="goodsPieChart" class="chart-container"></div>
            </el-card>
        </div>

        <!-- 详细统计卡片区域 -->
        <div class="stats-cards">
            <div class="card">
                <div class="card-value" style="color: green;">{{inventoryInquiry.inStockQuantity || 0}}</div>
                <div class="card-label">入库数量</div>
            </div>
            <div class="card">
                <div class="card-value" style="color: orange;">{{inventoryInquiry.outStockQuantity || 0}}</div>
                <div class="card-label">出库数量</div>
            </div>
            <div class="card">
                <div class="card-value" style="color: green;">{{inventoryInquiry.unInStockQuantity || 0}}</div>
                <div class="card-label">待入库</div>
            </div>
            <div class="card">
                <div class="card-value" style="color: orange;">{{inventoryInquiry.totalPlannedQuantity || 0}}</div>
                <div class="card-label">待出库</div>
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="btnAndTable">
            <el-table :data="paginatedData"
                      style="width: 100%; margin-top: 10px"
                      ref="multipleTable"
                      stripe
                      border>
                <el-table-column type="" width="50"></el-table-column>
                <el-table-column prop="goodsCode"
                                 label="货品编号"
                                 width="150">
                </el-table-column>
                <el-table-column prop="goodsName"
                                 label="货品名称"
                                 width="200">
                </el-table-column>
                <el-table-column prop="status"
                                 label="状态"
                                 width="100">
                </el-table-column>
                <el-table-column prop="goodsTypeName"
                                 label="货品类型"
                                 width="120">
                </el-table-column>
                <el-table-column prop="specification"
                                 label="规格型号"
                                 width="120">
                </el-table-column>
                <el-table-column prop="warehouseName"
                                 label="仓库名称"
                                 width="120">
                </el-table-column>
                <el-table-column prop="storageLocationName"
                                 label="库位名称"
                                 width="120">
                </el-table-column>
                <el-table-column prop="currentInventory"
                                 label="当前库存"
                                 width="100">
                </el-table-column>
                <el-table-column prop="inventoryAmount"
                                 label="库存金额"
                                 width="100">
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="130">
                    <template #default="scope">
                        <el-button class="operate-btn" link type="primary" size="default">出入库流水</el-button>
                        <el-button class="operate-btn" link type="primary" size="default">库存分布</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage"
                           v-model:page-size="pageSize"
                           :page-sizes="[10, 20, 50, 100]"
                           :total="total"
                           layout="total, sizes, prev, pager, next, jumper"
                           v-on:size-change="handleSizeChange"
                           v-on:current-change="handleCurrentChange">
            </el-pagination>
        </div>
    </div>
</div>

<script>
    const { createApp, ref, onMounted, computed, onUnmounted } = Vue;
    const { ElMessage, ElNotification } = ElementPlus;

    const app = createApp({
        setup() {
            // -------------------------- 1. 基础数据初始化 --------------------------
            // 搜索表单
            const searchForm = ref({
                goodsName: '',
                goodsType: '',
                unit: '',
                warehouseName: '',
                goodsBarcode: '',
                showDisabled: false,
                filterZeroStock: false
            });

            // 库存查询数据 - 添加更完整的默认值
            const inventoryInquiry = ref({
                totalPlannedQuantity: 0,
                availableInventoryQty: 0,
                priceAvailableInventoryQty: 0,
                outStockQuantity: 0,
                inStockQuantity: 0,
                unInStockQuantity: 0
            });

            // 概览数据
            const overviewData = ref({
                totalInventory: 0,
                totalInventoryValue: 0,
                todayInbound: 0,
                todayOutbound: 0,
                pendingApprovals: 0,
                inventoryAlerts: 0,
                inventoryTrend: 0,
                valueTrend: 0,
                inboundTrend: 0,
                outboundTrend: 0
            });

            // 饼图数据
            const pieChartData = ref([]);
            const goodsPieChartData = ref([]);
            let pieChart = null;
            let goodsPieChart = null;

            // 表格数据
            const tableData = ref([]);
            const multipleTable = ref(null);

            // 分页相关
            const currentPage = ref(1);
            const pageSize = ref(10);
            const total = computed(() => tableData.value.length);
            const paginatedData = computed(() => {
                const start = (currentPage.value - 1) * pageSize.value;
                const end = start + pageSize.value;
                return tableData.value.slice(start, end);
            });

            // -------------------------- 2. 方法定义 --------------------------
            // 初始化饼图
            const initPieChart = () => {
                const chartDom = document.getElementById('categoryPieChart');
                if (!chartDom) {
                    console.warn('饼图容器未找到');
                    return;
                }

                pieChart = echarts.init(chartDom);
                updatePieChart();
            };

            // 初始化货品饼图
            const initGoodsPieChart = () => {
                const chartDom = document.getElementById('goodsPieChart');
                if (!chartDom) {
                    console.warn('货品饼图容器未找到');
                    return;
                }

                goodsPieChart = echarts.init(chartDom);
                updateGoodsPieChart();
            };

            // 更新饼图数据
            const updatePieChart = () => {
                if (!pieChart || !tableData.value.length) return;

                // 从表格数据中统计各货品类型的库存数量
                const typeStats = {};
                tableData.value.forEach(item => {
                    const type = item.goodsTypeName || '其他';
                    const inventory = Number(item.currentInventory) || 0;

                    if (typeStats[type]) {
                        typeStats[type] += inventory;
                    } else {
                        typeStats[type] = inventory;
                    }
                });

                // 转换为饼图数据格式
                const pieData = Object.keys(typeStats).map(type => ({
                    name: type,
                    value: typeStats[type]
                }));

                pieChartData.value = pieData;

                const option = {
                    title: {
                        text: '库存类型分布',
                        left: 'center',
                        textStyle: {
                            fontSize: 16,
                            fontWeight: 'normal'
                        }
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        type: 'scroll',
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    series: [
                        {
                            name: '库存数量',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            center: ['60%', '50%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 18,
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: pieData
                        }
                    ],
                    color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#B37FEB', '#FF85C0']
                };

                pieChart.setOption(option);
            };

            // 更新货品饼图数据
            const updateGoodsPieChart = () => {
                if (!goodsPieChart || !tableData.value.length) return;

                // 从表格数据中统计各货品的库存数量
                const goodsStats = {};
                tableData.value.forEach(item => {
                    const goodsName = item.goodsName || '未知货品';
                    const inventory = Number(item.currentInventory) || 0;

                    if (goodsStats[goodsName]) {
                        goodsStats[goodsName] += inventory;
                    } else {
                        goodsStats[goodsName] = inventory;
                    }
                });

                // 转换为饼图数据格式并排序（取前10个，其他的归为其他）
                let goodsData = Object.keys(goodsStats).map(goodsName => ({
                    name: goodsName,
                    value: goodsStats[goodsName]
                }));

                // 按库存数量降序排序
                goodsData.sort((a, b) => b.value - a.value);

                // 如果货品数量超过8个，只显示前7个，其他的归为"其他"
                if (goodsData.length > 8) {
                    const topGoods = goodsData.slice(0, 7);
                    const otherValue = goodsData.slice(7).reduce((sum, item) => sum + item.value, 0);

                    if (otherValue > 0) {
                        topGoods.push({
                            name: '其他',
                            value: otherValue
                        });
                    }
                    goodsData = topGoods;
                }

                goodsPieChartData.value = goodsData;

                const option = {
                    title: {
                        text: '货品库存占比',
                        left: 'center',
                        textStyle: {
                            fontSize: 16,
                            fontWeight: 'normal'
                        }
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        type: 'scroll',
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    series: [
                        {
                            name: '库存数量',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            center: ['60%', '50%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 18,
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: goodsData
                        }
                    ],
                    color: ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9']
                };

                goodsPieChart.setOption(option);
            };

            // 窗口resize事件处理
            const handleResize = () => {
                if (pieChart) {
                    pieChart.resize();
                }
                if (goodsPieChart) {
                    goodsPieChart.resize();
                }
            };

            // 分页处理
            const handleSizeChange = (val) => {
                pageSize.value = val;
                currentPage.value = 1;
            };

            const handleCurrentChange = (val) => {
                currentPage.value = val;
                if (multipleTable.value) {
                    multipleTable.value.clearSelection();
                }
            };

            // 数据加载
            const refreshData = async () => {
                try {
                    // 原有API调用
                    const response = await axios.post('/InventoryInquiry/IICAII');
                    if (response.data.code === 200) {
                        inventoryInquiry.value = {
                            ...inventoryInquiry.value,
                            ...response.data.data
                        };
                    }

                    const responsePIIU = await axios.post('/InventoryInquiry/PIIU');
                    if (responsePIIU.data.code === 200) {
                        tableData.value = responsePIIU.data.data || [];

                        // 数据加载完成后更新饼图
                        setTimeout(() => {
                            updatePieChart();
                            updateGoodsPieChart();
                        }, 100);
                    }

                    const apiData = inventoryInquiry.value;
                    // 生成-15%~15%的随机涨跌幅（保留1位小数）
                    const getRandomTrend = () => (Math.random() * 30 - 15).toFixed(1) * 1;

                    // 基于API数据计算带涨跌幅的概览数据
                    overviewData.value = {
                        totalInventory: apiData.availableInventoryQty || 0,
                        totalInventoryValue: apiData.priceAvailableInventoryQty || 0,
                        todayInbound: apiData.inStockQuantity || 0,
                        todayOutbound: apiData.outStockQuantity || 0,
                        pendingApprovals: 17,
                        inventoryAlerts: 8,
                        inventoryTrend: getRandomTrend(),
                        valueTrend: getRandomTrend(),
                        inboundTrend: getRandomTrend(),
                        outboundTrend: getRandomTrend()
                    };

                } catch (error) {
                    console.error('数据加载失败:', error);
                    ElMessage.error('数据加载失败，请重试');
                }
            };

            // 刷新表格
            const refreshTable = () => {
                if (multipleTable.value) {
                    multipleTable.value.clearSelection();
                }
                currentPage.value = 1;
                refreshData();
                ElMessage({ type: 'success', message: '表格已刷新！' });
            };

            // 重置表单
            const resetForm = () => {
                searchForm.value = {
                    goodsName: '',
                    goodsType: '',
                    unit: '',
                    warehouseName: '',
                    goodsBarcode: '',
                    showDisabled: false,
                    filterZeroStock: false
                };
                refreshTable();
            };

            // 查询
            const searchTable = () => {
                ElMessage({ type: 'success', message: '查询条件已应用！' });
            };

            // 导出
            const exportTable = () => {
                ElMessage({ type: 'success', message: '导出请求已触发，正在下载...' });
            };

            // -------------------------- 3. 生命周期 --------------------------
            onMounted(() => {
                refreshData();
                // 延迟初始化图表，确保DOM已渲染
                setTimeout(() => {
                    initPieChart();
                    initGoodsPieChart();
                }, 300);

                // 监听窗口大小变化
                window.addEventListener('resize', handleResize);
            });

            onUnmounted(() => {
                if (pieChart) {
                    pieChart.dispose();
                }
                if (goodsPieChart) {
                    goodsPieChart.dispose();
                }
                window.removeEventListener('resize', handleResize);
            });

            // 暴露数据和方法
            return {
                searchForm,
                tableData,
                paginatedData,
                multipleTable,
                currentPage,
                pageSize,
                total,
                inventoryInquiry,
                overviewData,
                pieChartData,
                goodsPieChartData,
                handleSizeChange,
                handleCurrentChange,
                refreshTable,
                resetForm,
                searchTable,
                exportTable
            };
        }
    });

    app.use(ElementPlus, {
            locale: ElementPlusLocaleZhCn
        });
    app.mount('#app');
</script>

<style>
    body {
        margin: 0;
        padding: 0;
        font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
        background-color: #f5f7fa;
    }

    #tableBlock {
        margin: 20px auto;
        width: 101%;
        padding-bottom: 20px;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        background-color: #fff;
        border-radius: 6px;
    }

    /* 图表区域样式 */
    .charts-section {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        padding: 20px;
    }

    .chart-card {
        border-radius: 8px;
        border: none;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        overflow: hidden;
    }

    .chart-header {
        font-size: 16px;
        font-weight: 500;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        border-bottom: 1px solid #f0f0f0;
    }

    .chart-container {
        width: 100%;
        height: 400px;
        padding: 15px;
    }

    .search-area {
        padding: 20px;
        border-bottom: 0px solid #ebeef5;
    }

    .formTableInput, .formTableSelect {
        display: inline-block;
        width: 180px;
    }

    .buttonBlock {
        height: 40px;
        width: 100%;
        padding: 20px;
        gap: 10px;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        padding: 0 20px;
    }

    .operate-btn {
        margin-right: 8px;
    }

    .btnAndTable {
        margin: 0 auto;
        padding: 0 20px;
    }

    .search-row {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 15px;
    }

    .search-item {
        display: flex;
        align-items: center;
    }

        .search-item label {
            min-width: 80px;
            text-align: right;
            margin-right: 10px;
        }

    /* 概览统计卡片样式 */
    .overview-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        padding: 20px 20px;
    }

    .stat-card {
        transition: all 0.3s ease;
        border-radius: 8px;
        border: none;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

    .stat-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px;
    }

    .stat-info {
        display: flex;
        flex-direction: column;
    }

    .stat-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
    }

    .stat-value {
        font-size: 28px;
        font-weight: 600;
        color: #333;
        margin-bottom: 5px;
    }

    .stat-trend {
        display: flex;
        align-items: center;
        font-size: 13px;
    }

        .stat-trend.up {
            color: #27ae60;
        }

        .stat-trend.down {
            color: #e74c3c;
        }

    .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
        color: #409eff;
        background-color: rgba(64, 158, 255, 0.1);
    }

    /* 详细统计卡片样式 */
    .stats-cards {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        padding: 0 20px 20px;
    }

    .card {
        background: #fff;
        border-radius: 6px;
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
        padding: 15px;
        min-width: 150px;
        text-align: center;
        flex: 1;
    }

    .card-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 5px;
    }

    .card-label {
        font-size: 14px;
        color: #666;
    }

    /* 响应式设计 */
    @@media (max-width: 1024px) {
        .charts-section

    {
        grid-template-columns: 1fr;
    }

    }

    @@media (max-width: 768px) {
        .charts-section

    {
        padding: 0 10px 20px;
    }

    .chart-container {
        height: 300px;
    }

    .overview-stats {
        grid-template-columns: repeat(2, 1fr);
    }

    .stats-cards {
        grid-template-columns: repeat(2, 1fr);
    }

    }
</style>